package com.jhm.bing_fa_rong_qi;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/*
* 例子看ArrayBlockingQueue，这个例子一般，两个例子的实现过程一样
*/

public class LinkedBlockingQueueExample {
    public static void main(String[] args) {
        // 创建一个容量为5的LinkedBlockingQueue
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(5);

        // 生产者线程
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    String item = "Item " + i;
                    System.out.println("Producing: " + item);
                    queue.put(item); // 队列满了会阻塞
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    String item = queue.take(); // 队列为空会阻塞
                    System.out.println("Consuming: " + item);
                    TimeUnit.SECONDS.sleep(2);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}